package server

import (
	"encoding/json"
	"io"
	"net/http"
)

// http 上下文环境，用于封装http读取请求参数，以及返回值的结构体
type HttpContext struct {
	R *http.Request
	W http.ResponseWriter
}

// 读取请求中Body中参数，并转化成相应的json对象
func (c *HttpContext) ReadJson(data interface{}) error {

	//这里只能读取一次Body的数据
	body, err := io.ReadAll(c.R.Body)
	if err != nil {
		return err
	}
	return json.Unmarshal(body, data)
}

func (c *HttpContext) ReadQueryURI(data interface{}) error {
	values := c.R.URL.Query()
	valuesByte, err := json.Marshal(values)
	if err != nil {
		return err
	}
	return json.Unmarshal(valuesByte, data)
}

func (c *HttpContext) WriteJson(status int, message string, data interface{}) error {
	c.W.WriteHeader(status)
	resBody := &ResponseBody{
		Code:    status,
		Message: message,
		Data:    &data,
	}
	resBytes, err := json.Marshal(resBody)
	if err != nil {
		return err
	}
	c.W.Write(resBytes)
	return nil
}

// ResponseBody 定义通用的返回结果
type ResponseBody struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

type RequestBody struct {
	data interface{}
}
